package com.taotao.rest.service.ipml;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.common.utils.JsonUtils;
import com.taotao.mapper.TbItemCatMapper;
import com.taotao.pojo.TbItemCat;
import com.taotao.pojo.TbItemCatExample;
import com.taotao.pojo.TbItemCatExample.Criteria;
import com.taotao.rest.dao.IJedisClient;
import com.taotao.rest.pojo.CatNode;
import com.taotao.rest.pojo.CatResult;
import com.taotao.rest.service.IItemCatService;

@Service
public class ItemCatServiceIpml implements IItemCatService {
	@Autowired
	private TbItemCatMapper itemCatMapper;

	@Autowired
	private IJedisClient jedisClient;

	@Value("${INDEX_ITEM_CAT_REDIS_KEY}")
	private String INDEX_ITEM_CAT_REDIS_KEY;

	/**
	 * 获取分类信息
	 */
	@Override
	public CatResult getItemCat() {
		// 获取redis中的内容
		try {
			String hget = this.jedisClient.hget(INDEX_ITEM_CAT_REDIS_KEY,
					IItemCatService.ITEM_CAT_INFO);
			if (StringUtils.isNoneBlank(hget)) {
				CatResult catResult = JsonUtils.jsonToPojo(hget,
						CatResult.class);
				return catResult;
			}

		} catch (Exception e) {
			// TODO: handle exception
		}
		CatResult catResult = new CatResult();
		List<?> itemCatList = getItemCatList(0L);
		// 选取前十四个分类信息
		itemCatList = itemCatList.subList(0, 14);
		catResult.setData(itemCatList);
		// 向redis中添加内容
		try {
			String jsonStr = JsonUtils.objectToJson(catResult);
			this.jedisClient.hset(INDEX_ITEM_CAT_REDIS_KEY,
					IItemCatService.ITEM_CAT_INFO, jsonStr);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return catResult;

	}

	/**
	 * 根据父节点获取全部分类信息
	 * 
	 * @param parentId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<?> getItemCatList(Long parentId) {
		TbItemCatExample example = new TbItemCatExample();
		Criteria criteria = example.createCriteria();
		criteria.andParentIdEqualTo(parentId);
		// 进行查询
		List<TbItemCat> itemCats = this.itemCatMapper.selectByExample(example);
		List catNodes = new ArrayList<CatNode>();
		for (TbItemCat itemCat : itemCats) {
			CatNode catNode = new CatNode();
			if (itemCat.getIsParent()) {
				// 设置地址
				catNode.setUrl("/products/" + itemCat.getId() + ".html");
				if (itemCat.getParentId() == 0L) {
					// 设置地址名称
					catNode.setName("<a href='/products/" + itemCat.getId()
							+ ".html'>" + itemCat.getName() + "</a>");
				} else {
					catNode.setName(itemCat.getName());
				}
				// 设置子节点
				catNode.setItems(getItemCatList(itemCat.getId()));
				catNodes.add(catNode);
			} else {
				catNodes.add("/products/" + itemCat.getId() + ".html|"
						+ itemCat.getName());
			}
		}
		return catNodes;
	}
}
